//
//  JNCardSDKFVRepayCtr.m
//  IDCardManager
//
//  Created by 金牛 on 2017/11/15.
//  Copyright © 2017年 zou. All rights reserved.
//

#import "JNCardSDKFVRepayCtr.h"
#import "JNCardSDKFVRepayCell.h"
#import "JNCardSDKFVRepayCellModel.h"
#import "JNCardSDKCardDetailVC.h"
#import "JNCardSDKAddNewCardVC.h"
#import "JNCardSDKNewRepayPlanVC.h"
#import "JNCardSDKAddBankCellModel.h"
#import "HDAlertView.h"
#import <objc/runtime.h>
@interface JNCardSDKFVRepayCtr ()<UITableViewDelegate,UITableViewDataSource>
{
    NSMutableArray * _dataArr;
    NSInteger _page;
    BOOL _isAllowAddCard/*验证实名有效性之前不让他点击添加信用卡按钮*/;
    UIAlertController * _alertCtr;
}
@property(nonatomic,retain)UITableView * myTab;
@property(nonatomic,retain)UIView * noDataView;
@end

@implementation JNCardSDKFVRepayCtr

- (void)viewDidLoad {
    [super viewDidLoad];
    NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(notifyReloadData) name:@"reloadcardplandetail" object:nil];
    self.view.backgroundColor = [UIColor colorWithRed:0.93 green:0.93 blue:0.93 alpha:1];
    self.myTitle = objc_getAssociatedObject(self, (__bridge const void * _Nonnull)(self));
    _dataArr = [NSMutableArray new];
    _page = 1;
    [self createUI];
    [self.view addSubview:self.myTab];
    [self checkoutUserCards];//网络请求用户卡片信息
}
-(void)notifyReloadData{
    self->_page = 1;
    [_dataArr removeAllObjects];
    [self checkoutUserCards];
}

-(void)createUI{
    UIButton * addBtn = [UIButton new];
    addBtn.backgroundColor = [UIColor whiteColor];
    [addBtn setImage:Image(@"add_fv") forState:0];
    addBtn.layer.cornerRadius = 6;
    [addBtn setTitleColor:[UIColor colorWithHue:0.56 saturation:0.98 brightness:1 alpha:1] forState:0];
    [addBtn addTarget:self action:@selector(addBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [addBtn setTitle:@"添加卡片" forState:0];
    [self.view addSubview:addBtn];
    addBtn.sd_layout.leftSpaceToView(self.view, 20).rightSpaceToView(self.view, 20).topSpaceToView(self.view, kTopHeight + 15).heightIs(45);
    [self addShadowToView:addBtn withColor:[UIColor colorWithRed:0.6 green:0.6 blue:0.6 alpha:1]];
    
    UIView * manageView = [UIView new];
    manageView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:manageView];
    manageView.sd_layout.leftEqualToView(self.view).rightEqualToView(self.view).topSpaceToView(addBtn, 15).heightIs(55);
    UIImageView * manageImg = [UIImageView new];
    manageImg.image = Image(@"计划管理");
    [manageView addSubview:manageImg];
    manageImg.sd_layout.leftSpaceToView(manageView, 10).centerYEqualToView(manageView).widthIs(30).heightEqualToWidth();
    UILabel * titleLab = [UILabel labelWithTitle:@"计划管理" color:[UIColor blackColor] font:[UIFont systemFontOfSize:17]]; 
    [manageView addSubview:titleLab];
    titleLab.sd_layout.leftSpaceToView(manageImg, 10).centerYEqualToView(manageView).heightIs(20);
    [titleLab setSingleLineAutoResizeWithMaxWidth:200];
    [self.view addSubview:self.myTab];
    
}
- (void)addShadowToView:(UIView *)theView withColor:(UIColor *)theColor {
    // 阴影颜色
    theView.layer.shadowColor = theColor.CGColor;
    // 阴影偏移，默认(0, -3)
    theView.layer.shadowOffset = CGSizeMake(0,0);
    // 阴影透明度，默认0
    theView.layer.shadowOpacity = 0.5;
    // 阴影半径，默认3
    theView.layer.shadowRadius = 5;
    
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataArr.count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    JNCardSDKFVRepayCell * cell = nil;
    if (!cell) {
        cell = [[JNCardSDKFVRepayCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@""];
        if (_dataArr.count!=0) {
            JNCardSDKFVRepayCellModel * model = _dataArr[indexPath.row];
            cell.model = model;
            //            cell.btnBlock = ^(NSString *stateStr) {
            //                if ([stateStr isEqualToString:@"制定计划"]) {
            //                    NSDictionary * dic = [JNCardSDKReuserFile newPlanBtnClick:model.BillDate andPayStr:model.DueDate andCardModel:(JNCardSDKCardCellModel*)model];
            //                    if ([dic[@"state"]isEqualToString:@"0"]) {
            //                        [JNCardSDKMytools warnText:dic[@"msg"] status:JNCardSDKError];
            //                        return;
            //                    }else{
            //                        [self gotoNextViewCtr:dic[@"billday"] andPayDayStr:dic[@"payday"] andModel:(JNCardSDKCardCellModel*)model];
            //                    }
            //                }else if ([stateStr isEqualToString:@"查看计划"]){
            //                    [self selectCell:indexPath];
            //                }else if ([stateStr isEqualToString:@"查看明细"]){
            //                    RepayPlanDetailVC * vc = [RepayPlanDetailVC new];
            //                    vc.myTitle = @"计划详情";
            //                    vc.planID = model.UserRepayPlayId;
            //                    [self.navigationController pushViewController:vc animated:YES];
            //                }else{
            //                    [JNCardSDKMytools warnText:@"返回异常" status:JNCardSDKError];
            //                }
            //            };
        }
        
    }
    return cell;
}
-(void)gotoNextViewCtr:(NSString *)billDayStr andPayDayStr:(NSString*)payDayStr andModel:(JNCardSDKCardCellModel*)model{
    JNCardSDKNewRepayPlanVC * vc = [[JNCardSDKNewRepayPlanVC alloc]init]; 
    vc.myTitle = @"创建还款计划";
    vc.myPlanType = 1;
    vc.billDay = billDayStr;
    vc.payDay = payDayStr;
    vc.bankCardID = model.userCreditCardId;
    vc.cardInfoModel=model;
    [self.navigationController pushViewController:vc animated:YES];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_dataArr.count!=0) {
        JNCardSDKFVRepayCellModel * model = _dataArr[indexPath.row];
        CGFloat height = [self.myTab cellHeightForIndexPath:indexPath model:model keyPath:@"model" cellClass:[JNCardSDKFVRepayCell class] contentViewWidth:[self cellContentViewWith]];
        return height;
    }else{
        return 0.01;
    }
    
}
- (CGFloat)cellContentViewWith{
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    return width;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (_dataArr.count!=0) {
        JNCardSDKFVRepayCellModel * model = _dataArr[indexPath.row];
        if (model.dueDate.length==0) {
            JNCardSDKAddNewCardVC * vc = [[JNCardSDKAddNewCardVC alloc]init];
            vc.bankModel = (JNCardSDKAddBankCellModel*)model;
            [self.navigationController pushViewController:vc animated:YES];
        }else{
            [self selectCell:indexPath];
        }
    }
}
-(void)selectCell:(NSIndexPath*)indexPath{
    JNCardSDKFVRepayCellModel * model = _dataArr[indexPath.row];
    JNCardSDKCardDetailVC * vc = [JNCardSDKCardDetailVC new];
    vc.cardInfoModel = (JNCardSDKCardCellModel*)model;
    vc.userCreditCardId = model.userCreditCardId;
    vc.myTitle = model.bankName;
    vc.notifyJNCardSDKTabBlock = ^{
        [self checkoutUserCards];
    };
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark 请求
-(void)checkoutUserCards{
    [SVProgressHUD show];
    //请求数据
    NSMutableDictionary * p = [JNCardSDKReuserFile returnHYKBaseDic];
    [p setObject:[NSString stringWithFormat:@"%ld",(long)_page] forKey:@"currentpage"];
    [p setObject:@"30" forKey:@"pagelimit"];
    NSString *utf = [JNCardSDKWorkUrl returnURL:Interface_For_GetUserBankList];
    [SVProgressHUD show];
    [PGNetworkHelper GET:utf parameters:p cache:NO responseCache:nil success:^(id responseObject) {
        [SVProgressHUD dismiss];
        if ([responseObject[@"status"]isEqualToString:@"1"]) {
            NSArray * dataArr = responseObject[@"data"];
            NSMutableArray * fuckArr = [NSMutableArray new];
            NSMutableArray * fillArr = [NSMutableArray new];
            for (NSDictionary * dic in dataArr) {
                if ([dic[@"DueDate"]isKindOfClass:[NSNull class]]) {
                    [fuckArr addObject:dic];
                }else{
                    [fillArr addObject:dic];
                }
            }
            [fillArr addObjectsFromArray:fuckArr.copy];
            NSMutableArray * arrM = [NSMutableArray arrayWithArray:[JNCardSDKFVRepayCellModel mj_objectArrayWithKeyValuesArray:fillArr]];
            [self->_dataArr addObjectsFromArray:arrM];
            [self->_myTab reloadData];
            [self NeedResetNoView];
        }else{
            [JNCardSDKMytools warnText:responseObject[@"msg"] status:JNCardSDKError]; 
        }
        [self->_myTab.mj_header endRefreshing];
        [self->_myTab.mj_footer endRefreshing];
        if ([responseObject[@"count"] integerValue]==self->_dataArr.count) {
            [self->_myTab.mj_footer endRefreshingWithNoMoreData];
        }
    } failure:^(NSError *error) {
        [SVProgressHUD dismiss];
    }];
}
-(void)addBtnClick{
    JNCardSDKAddNewCardVC * vc = [[JNCardSDKAddNewCardVC alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark 懒加载
-(UITableView*)myTab{
    if (_myTab == nil) {
        _myTab = [[UITableView alloc]initWithFrame:CGRectMake(0, kTopHeight+130, IPHONE_WIDTH, IPHONE_HEIGHT-kTopHeight-130-kTabbarHeight) style:UITableViewStyleGrouped];
        _myTab.delegate = self;
        _myTab.dataSource =self;
        _myTab.showsVerticalScrollIndicator = NO;
        _myTab.backgroundColor = [UIColor whiteColor];
        _myTab.separatorStyle = UITableViewCellSeparatorStyleNone;
        _myTab.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{ 
            self->_page = 1;
            [self->_dataArr removeAllObjects];
            [self checkoutUserCards];
        }];
        _myTab.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            self->_page ++;
            [self checkoutUserCards];
        }];
    }
    return _myTab;
}
-(UIView*)noDataView{
    UIView * view=[[UIView alloc]initWithFrame:CGRectMake(0, kTopHeight+114, IPHONE_WIDTH, IPHONE_HEIGHT-kTopHeight-114-kTabbarHeight)];
    view.backgroundColor=[UIColor whiteColor];
    UIImageView*img=[UIImageView new];
    img.image=[UIImage imageNamed:@"暂无数据_shanghuruwang"];
    [view addSubview:img];
    img.sd_layout.centerXEqualToView(view).topSpaceToView(view, 93).widthIs(267).heightIs(145);
    
    UILabel*label=[UILabel new];
    label.text=@"暂无数据";
    label.font=[UIFont systemFontOfSize:16];
    label.textColor=[UIColor colorWithRed:153/255.0 green:153/255.0 blue:153/255.0 alpha:1];
    label.textAlignment=NSTextAlignmentCenter;
    [view addSubview:label];
    label.sd_layout.topSpaceToView(img,44).centerXEqualToView(view).widthIs(100).autoHeightRatio(0);
    
    return view;
}
- (void)NeedResetNoView{
    if (_dataArr.count>0) {
        [self.myTab dismissNoView];
    }else{
        [self.myTab dismissNoView];
        [self.myTab showNoView:@"暂无数据" image:nil certer:CGPointZero];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end

